<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of LoginService
 *
 * @author Administrator
 */

namespace frontend\service\user;

use frontend\bean\User;
use frontend\enum;
use Yii;
use frontend\library\oauth2\OAuth2_Token;
use frontend\library\oauth2\providers\OAuth2_Qq;
use frontend\library\oauth2\providers\OAuth2_Weibo;
use frontend\dao\UserDao;
use frontend\library\MT;
use frontend\exception\UserException;
use frontend\enum\ThirdType;

//use yii\web\User;

class UserService {

    private $user;
    private $userBind;
    private $userDao;

    public function __construct(UserDao $userDao) {


        $this->userDao = $userDao;
        Yii::$app->getUser()->on(\yii\web\User::EVENT_BEFORE_LOGIN, function($event) {
           
            
        });
    }

    function getUserBind() {
        return $this->userBind;
    }

    function setUserBind($userBind) {
        $this->userBind = $userBind;
    }

    function getUser() {
        return $this->user;
    }

    function setUser(User $user) {
        $this->user = $user;
    }

    /*
     * 第三方登陆
     */

    public function loginByThird($type, $type_uid, $oauth_token) {
        $token = new OAuth2_Token($oauth_token);
     
        if ($type == ThirdType::QQ) {
            $provider = new OAuth2_Qq(Yii::$app->params['oauth']);
        } elseif (ThirdType::WeiBo) {
            $provider = new OAuth2_Weibo(Yii::$app->params['oauth']);
        }
        $third_uid = $provider->getUserId($token);
        if ($third_uid != $type_uid) {
            throw  new UserException(UserException::E_OAUTH_UID_INVAILD);
        }
        
        
        
    }

    /*
     * @param number $mobile
     * @param string $password
     */

    public function loginByMobile($mobile, $password) {
        
        $user = $this->userDao->getUserByMobile($mobile);
        
        if ($user) {
            if (MT::buildPassword($password, $user['salt']) != $user['password']) {
                 
                throw  new UserException( UserException::E_USER_PASSWORD_ERROR);
            }

            Yii::$app->user->login($user);
          } else {
           throw  new UserException( UserException::E_USER_NOT_RESIGTER);
        }
    }

    public function mobileRegister() {
        $third_uid = $this->authOAuthUid($userBindDm->getField('type'), $userBindDm->getField('type_uid'), $userBindDm->getField('oauth_token'));
    }

    /*
     * 手机用户注册
     */


    /*
      public function mobileRegister(UserBindDm $userBindDm, UserDm $userDm) {
      Yii::import('application.service.user.UserBindDs');
      Yii::import('application.service.user.UserDs');
      Yii::import('application.service.user.validator.UserValidator');
      Yii::import('application.library.enum.MtEnum');
      Yii::import('application.service.user.bo.UserBo');

      $third_uid = $this->authOAuthUid($userBindDm->getField('type'), $userBindDm->getField('type_uid'), $userBindDm->getField('oauth_token'));
      if ($third_uid instanceof BaseError) {
      return $third_uid;
      }
      $userBindDs = new UserBindDs();
      $record = $userBindDs->getBindRecordByTypeId($userBindDm->getField('type'), $userBindDm->getField('type_uid'));
      if ($record && $record->uid > 0) {
      return new BaseError(BaseError::E_USER_HAS_REGISTER);
      }
      #check username
      $userDs = new UserDs();
      $r = UserValidator::isUsernameValid($userDm->getField('username'));
      if ($r instanceof BaseError) {
      return $r;
      }
      if ($userBindDm->getField('type') == MtEnum::$bind['test']) {
      $userDm->setGroup(rand(MtEnum::$user_group['childhood'], MtEnum::$user_group['college']));
      } else {
      $userDm->setGroup(MtEnum::$user_group['childhood']);
      }

      //先添加用户然后绑定关系
      if (($r = $userDs->addUser($userDm) )instanceof BaseError) {
      return $r;
      } else {

      $userDm->setUid($r);
      $userBindDm->setUid($r);
      $userBindDs->addBind($userBindDm);
      //设置当前登陆用户
      $bo = new UserBo($r);
      self::setLoginUser($bo);

      return $bo;
      }
      }

      /*
     * 手机用户邮箱注册
     */

    public function mobileRegisterByEmail(UserBindDm $userBindDm, UserDm $userDm) {
        Yii::import('application.service.user.UserDs');
        Yii::import('application.service.user.bo.UserBo');
        Yii::import('application.service.user.validator.UserValidator');
        Yii::import('application.library.enum.MtEnum');
        $userNameIsVaild = UserValidator::isUsernameValid($userDm->getField('username'));
        if ($userNameIsVaild instanceof BaseError) {
            return $userNameIsVaild;
        }
        $userEmailIsVaild = UserValidator::isEmailValid($userBindDm->getField('type_uid'));
        if ($userEmailIsVaild instanceof BaseError) {
            return $userEmailIsVaild;
        }
        $passWordIsVaild = UserValidator::isPassWordVaild($userBindDm->getField('oauth_token'));
        if ($passWordIsVaild instanceof BaseError) {
            return $passWordIsVaild;
        }
        $userDs = new UserDs();
        $userDm->setEmail($userBindDm->getField('type_uid'))
                ->setPassWord($userBindDm->getField('oauth_token'));
        if (($addRes = $userDs->addUser($userDm) )instanceof BaseError) {
            return $addRes;
        } else {

            $userDm->setGroup(MtEnum::$user_group['childhood']);
            //设置当前登陆用户
            $bo = new UserBo($addRes);
            self::setLoginUser($bo);

            return $bo;
        }
    }

    /*
      用户名注册
     */

    public function mobileRegisterByUserName(UserBindDm $userBindDm, UserDm $userDm) {
        Yii::import('application.service.user.UserDs');
        Yii::import('application.service.user.bo.UserBo');
        Yii::import('application.service.user.validator.UserValidator');
        Yii::import('application.library.enum.MtEnum');
        $userNameIsVaild = UserValidator::isUsernameValid($userBindDm->getField('type_uid'));
        if ($userNameIsVaild instanceof BaseError) {
            return $userNameIsVaild;
        }
        $passWordIsVaild = UserValidator::isPassWordVaild($userBindDm->getField('oauth_token'));
        if ($passWordIsVaild instanceof BaseError) {
            return $passWordIsVaild;
        }
        $userDs = new UserDs();
        $userDm->setUserName($userBindDm->getField('type_uid'))
                ->setPassWord($userBindDm->getField('oauth_token'));
        if (($addRes = $userDs->addUser($userDm) )instanceof BaseError) {
            return $addRes;
        } else {

            $userDm->setGroup(MtEnum::$user_group['childhood']);
            //设置当前登陆用户
            $bo = new UserBo($addRes);
            self::setLoginUser($bo);

            return $bo;
        }
    }

    /*
     * 获取用户基本信息，等级，在线情况
     */

    public function getUserDetail($uid) {
        Yii::import('application.service.usergroup.UserGroupDs');
        $g_ds = new UserGroupDs();
        $ds = new UserDs();
        $r = $ds->getUserById($uid);
        if ($r instanceof User) {
            $group = $g_ds->getGroupByGid($r->gid);
            if ($group instanceof UserGroup) {
                $r->level = $group->level;
            }
        }

        return $r;
    }

    public function authOAuthUid($type, $type_uid, $oauth_token) {
        //带*只是针对当前文件夹，不会深入子文件夹
        Yii::import('application.library.enum.MtEnum');
        Yii::import('application.library.oauth2.*');
        Yii::import('application.library.oauth2.providers.*');

        try {

            $token = new OAuth2_Token($oauth_token);
            if ($type == MtEnum::$bind['qq']) {
                $provider = new OAuth2_Qq(Yii::app()->params['oauth']);
            } elseif (MtEnum::$bind['weibo']) {
                $provider = new OAuth2_Weibo(Yii::app()->params['oauth']);
            } else {
                return new BaseError(BaseError::E_OAUTH_TYPE_UNSUPPORT);
            }

            $third_uid = $provider->getUserId($token);
            if ($third_uid != $type_uid) {
                return new BaseError(BaseError::E_OAUTH_UID_INVAILD);
            }
        } catch (Exception $e) {
            return new BaseError(BaseError::E_OAUTH_TOKEN_INVAILD);
        }
    }

    /*
     * 手机登录
     * @param int type
     * @param int type_uid
     */

    public function mobileLogin($type, $type_uid, $oauth_token) {

        Yii::import('application.service.user.UserBindDs');
        Yii::import('application.service.user.bo.UserBo');
        Yii::import('application.service.user.UserSessionDs');
        $third_uid = $this->authOAuthUid($type, $type_uid, $oauth_token);
        if ($third_uid instanceof BaseError) {
            return $third_uid;
        }
        $userBindDs = new UserBindDs();
        $record = $userBindDs->getBindRecordByTypeId($type, $type_uid);
        if ($record && $record->uid > 0) {#find user in db
            // $userDs = new UserDs();
            $bo = new UserBo($record->uid);
            // $user = $userDs->getUserById($record->uid);
            if ($bo->isExists()) { #生成token
                #find the session
                $this->runDo('loginBefore', $bo);
                $this->setLoginUser($bo);
                $this->runDo('loginAfter', self::$userbo);
                return $bo;
                /*
                  if ($this->limit_single_login) {#只允许单个登陆
                  $sessionDs = new UserSessionDs();
                  $session = $sessionDs->getSessionByUid($bo->uid);
                  if ($session) {
                  $sessionDs->delSession($session->sid);
                  //return new BaseError(BaseError::E_USER_HAS_LOGIN);
                  //  } else {
                  }
                  $this->setLoginUser($bo);
                  $this->runDo('loginAfter', self::$userbo);
                  return $bo;
                  } else {
                  $this->setLoginUser($bo);
                  $this->runDo('loginAfter', self::$userbo);
                  return $bo;
                  } */
            } else {
                return new BaseError(BaseError::E_USER_INFO_EXECPTION);
            }
        } else {
            return new BaseError(BaseError::E_USER_NOT_RESIGTER);
        }
    }

    /*
     * 手机邮箱登录(非第三方登陆)
     * @param string email
     * @param string password
     */

    public function mobileLoginByEmail($email, $password) {
        Yii::import('application.service.user.UserDs');
        Yii::import('application.service.user.bo.UserBo');
        $userDs = new UserDs();
        $userInfo = $userDs->getUserByEmail($email);
        if (!$userInfo) {
            return new BaseError(BaseError::E_USER_NOT_RESIGTER);
        }
        // $userInfo = $userEmailIsExist;

        if (MT::buildPassword($password, $userInfo['salt']) != $userInfo['password']) {
            return new BaseError(BaseError::E_USER_PASSWORD_ERROR);
        } else {
            $bo = new UserBo($userInfo->uid);
            $this->runDo('loginBefore', $bo);
            $this->setLoginUser($bo);
            $this->runDo('loginAfter', self::$userbo); //var_dump($bo);exit();
            return $bo;
        }
    }

    /*
      手机用户名登陆
     * @param string username
     * @param string password
     */

    public function mobileLoginByUserName($username, $password) {
        Yii::import('application.service.user.UserDs');
        Yii::import('application.service.user.bo.UserBo');
        $userDs = new UserDs();
        $userInfo = $userDs->getUserByName($username);
        if (!$userInfo) {
            return new BaseError(BaseError::E_USER_NOT_RESIGTER);
        }
        // $userInfo = $userEmailIsExist;

        if (MT::buildPassword($password, $userInfo['salt']) != $userInfo['password']) {
            return new BaseError(BaseError::E_USER_PASSWORD_ERROR);
        } else {
            $bo = new UserBo($userInfo->uid);
            $this->runDo('loginBefore', $bo);
            $this->setLoginUser($bo);
            $this->runDo('loginAfter', self::$userbo);
            return $bo;
        }
    }

    /*
     * 手机退出接口
     * @param sid
     */

    public function mobileLogout($sid) {
        Yii::import('application.service.user.UserSessionDs');
        $ds = new UserSessionDs();
        $session = $ds->getUidBySid($sid);
        if (!$session) {
            return new BaseError(BaseError::E_SESSSION_INVAILD);
        } else {
            $ds->delSession($sid);
        }
        return true;
        /*
          $loginUser = Wekit::getLoginUser();
          PwSimpleHook::getInstance('PwUserService_logout')->runDo($loginUser);
          $loginUser->reset();
          return Pw::setCookie('winduser', '', -1); */
    }

    /*
     * 设置登录token   
     */

    public function setLoginToken($u) {
        Yii::import('application.service.user.UserSessionDs');
        Yii::import('application.service.user.dm.UserSessionDm');
        $sessionDs = new UserSessionDs();
        $dm = new UserSessionDm();
        $dm->setUid($u->uid)
                ->setGid($u->gid)
                ->setSid(MT::genToken());
        $sessionDs->addSession($dm);
        return $dm->getField('sid');
    }

    public function getLoginToken($token) {
        Yii::import('application.service.user.UserSessionDs');
        $userSessionDs = new UserSessionDs;
        return $userSessionDs->getUidBySid($token);
    }

    public function checkUserHasLogin($uid) {
        
    }

    public function clearLoginToken($sid) {
        
    }

    /*
     * 设置登录cookie
     */

    public function setLoginCookie() {
        
    }

    /*
     * 注册后期要做的逻辑
     */

    protected function afterRegister(UserInfoDm $userDm) {
        
    }

    /*
     * web登录
     */

    public function webLogin() {
        
    }

    private function _getAppDs() {
        return Wekit::load('WSRV:app.WindidApp');
    }

    private function getUserBindDs() {
        Yii::import('application.service.UserBindDs');
        return UserBindDs::getInstance();
    }

    private function _getUserDs() {
        Yii::import('application.service.UserDs');
        return UserDs::getInstance();
        //  return Wekit::load('WSRV:user.WindidUser');
    }

    private function _getUserSessionDs() {
        return Wekit::load('WSRV:user.WindidUser');
    }

    private function _getUserBlackDs() {
        return Wekit::load('WSRV:user.WindidUserBlack');
    }

    public function getTeachList($page = 1, $limit = 10, $ext = array()) {
        $ds = new UserDs();
        $gid = 8;
        $count = $ds->getTeachCount($gid, $ext);

        if ($count < 1) {
            return array(0, array());
        }
        list($start, $limit) = MT::page2limit($page, $limit);
        $userinfo = array();
        $list = $ds->getTeachList($gid, $start, $limit, $ext);

        foreach ($list as $v) {
            $user = User::model()->getUserById($v->uid);
            $user && $userinfo[] = $user;
        }

        //$list = User::model()->getUsersByIds($uids);

        return array($count, $userinfo);
    }

}
